问题描述
使用ajax传入动态数据到后台,动态数据是通过jquery获取到的数据并定义了变量名,当按照静态数据传送的方式传送时会报错,提示无法解析,报错如下:
1 | 2019-06-29 12:25:05,302 10042 [o-8080-exec-165] WARN efaultHandlerExceptionResolver - Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unrecognized token 'admin': was expecting ('true', 'false' or 'null'); nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'admin': was expecting ('true', 'false' or 'null') at [Source: (PushbackInputStream); line: 1, column: 19] |
代码如下:
1 | var username = $("#username").val(); |
原因分析
当dataType指定为json后,1.4+以上的jquery版本对json格式要求更加严格。如果不是严格的json格式,就不能正常执行success回调函数。
解决方法
将动态的object转化成json String类型,直接调用Json提供的函数即可,代码如下:
1 | data:'{"username":'+JSON.stringify(username)+', "password":'+JSON.stringify(password)+'}', |